import base64
from io import BytesIO
import requests

API_KEY = "4PmbS3DPbepPoi93dcWLgjT9"
SECRET_KEY = "ipsOAIGXuYoD3ybpPwYrxAExGUOZURZz"

def baidu_ocr(screenshot):
    buffered = BytesIO()
    screenshot.save(buffered, format="PNG")
    img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')  # 确保使用utf-8解码

    # 调用百度OCR接口（修正点2：参数格式调整）
    token = get_baiduaccess_token()
    url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic'
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    data = {
        'access_token': token,
        'image': img_base64,  # 参数名必须为image
        'language_type': 'ENG'
    }
    
    # 修正点3：使用params参数传递access_token
    params = {'access_token': token}
    payload = {
        'image': img_base64,
        'language_type': 'ENG'
    }
    
    # 发送请求（修正点4：使用data参数正确编码）
    response = requests.post(url, params=params, data=payload, headers=headers)
    print(response.text)
    

def get_baiduaccess_token():
    """
    使用 AK，SK 生成鉴权签名（Access Token）
    :return: access_token，或是None(如果错误)
    """
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
    return str(requests.post(url, params=params).json().get("access_token"))

 
